﻿using Common.Communal;
using ERP.Domain.Scheduling;
using MediatR;
using Scheduling.Api.Read.Application.Command.TeamCommand;
using SqlSugar;

namespace Scheduling.Api.Read.Application.CommandHandlers.TeamHandler
{
    public class TeamCreateCommandHandler : IRequestHandler<TeamCreateCommand, ApiResult<ApiPaging<Team>>>
    {
        public TeamCreateCommandHandler(ISqlSugarClient sqlSugar) 
        {
            SqlSugar = sqlSugar;
        }

        public ISqlSugarClient SqlSugar { get; }

        public Task<ApiResult<ApiPaging<Team>>> Handle(TeamCreateCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<Team>> result = new ApiResult<ApiPaging<Team>>();
            result.Code = EnumCode.Ok;
            result.Message = "班组显示成功";
            
            // 只查询IsDelete为false的记录
            var query = SqlSugar.Queryable<Team>().Where(x => x.IsDelete == false);
            var list = query.ToList();
            int totalcount = list.Count();
            int totalpage = (int)Math.Ceiling(totalcount*1.0 / request.pagesize);
            list = list.OrderBy(x => x.TeamId).Skip((request.pageindex - 1) * request.pagesize).Take(request.pagesize).ToList();
            ApiPaging<Team> paging = new ApiPaging<Team>();
            paging.TotalCount = totalcount;
            paging.TotalPage = totalpage;
            paging.Data = list.ToList();
            result.Data = paging;
            return Task.FromResult(result);
        }
    }
}
